﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace BOSS.Framework
{
    /// <summary>
    /// 默认密码加密器
    /// </summary>
    public class PasswordCryptor
    {
        /// <summary>
        /// 默认实现
        /// </summary>
        public static readonly IPasswordCryptor Default = new Cryptor_Md5();

        /// <summary>
        /// 基于 MD5 的实现
        /// </summary>
        private class Cryptor_Md5 : IPasswordCryptor
        {
            #region IPasswordCryptor 成员

            /// <summary>
            /// 加密
            /// </summary>
            /// <param name="plain"></param>
            /// <returns></returns>
            public string Encrypt(string plain)
            {
                MD5 md5 = MD5.Create();
                byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(plain));
                StringBuilder hash = new StringBuilder();
                foreach (byte b in bytes)
                {
                    hash.Append(b.ToString("X2"));
                }

                md5.Initialize();
                bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(hash.ToString()));
                hash.Length = 0;
                foreach (byte b in bytes)
                {
                    hash.Append(b.ToString("X2"));
                }

                return hash.ToString();
            }

            #endregion
        }

    }
}
